package com.tledu.student_manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.tledu.student_manager.dao.UserDao;
import com.tledu.student_manager.exception.CustomException;
import com.tledu.student_manager.model.User;
import com.tledu.student_manager.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

@WebServlet("/user/add")
public class UserAddServlet extends HttpServlet {

    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        this.userService = new UserService(new UserDao());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/view/userAdd.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 封装参数
        User user = new User();
        user.setUsername(req.getParameter("username"));
        user.setPassword(req.getParameter("password"));
        user.setNickname(req.getParameter("nickname"));
        user.setAge(Integer.parseInt(req.getParameter("age")));
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            user.setBirthday(simpleDateFormat.parse(req.getParameter("birthday")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 封装好了参数
        try {
            userService.add(user);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 200);
            jsonObject.put("success", true);
            jsonObject.put("msg", "新曾成功");
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().println(jsonObject.toJSONString());
        } catch (CustomException e) {
            e.printStackTrace();
            // 报错的响应
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().println(jsonObject.toJSONString());
        }
    }
}
